package com.ebook.server.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ebook.core.domain.Book;
import com.ebook.core.domain.User;
import com.ebook.server.service.BookService;

/**
 * 我的书架
 * //TODO:拦截器里面实现先检查是否登录
 * @author a
 *
 */
@Controller
@RequestMapping(value = "/fav")
public class FavorController {

	@Resource
	BookService bookService;

	/**
	 * 可以按分类显示书架中的图书
	 */
	@RequestMapping(value = "/list")
	public String showBooks(Model model, HttpServletRequest request) {
		
		User user = (User)request.getSession().getAttribute("loginuser");
		if (user != null) {
			List<Book> favbooks = bookService.getFavBooksByUserId(user.getId());
			model.addAttribute("favbooks", favbooks);
			return "/fav/list";
		}
		else {
			model.addAttribute("error", true);
			model.addAttribute("errormsg", "只有注册用户才能创建书架！请先登录或免费注册.");
			return "/common/error";
		}
		
	}

	@RequestMapping(value = "/add")
	public String addBook(Model model, HttpServletRequest request) {
		try {
			int bookId = Integer.valueOf(request.getParameter("id"));
			User user = (User)request.getSession().getAttribute("loginuser");
		
			boolean success = bookService.addFavBook(user.getId(), bookId);
			if (!success) {
				model.addAttribute("error", true);
				model.addAttribute("errormsg", "收藏失败！");
				return "/common/error";
			}

		} catch (Exception e) {
			model.addAttribute("error", true);
			model.addAttribute("errormsg", "收藏失败！请先登录.");
			return "/common/error";
		}
		return "redirect:/fav/list";
	}
	
	@RequestMapping(value = "/del")
	public String delBook(Model model, HttpServletRequest request) {
		try {
			int bookId = Integer.valueOf(request.getParameter("id"));
			User user = (User)request.getSession().getAttribute("loginuser");
			bookService.deleteFavBook(user.getId(), bookId);
		} catch (Exception e) {
			model.addAttribute("error", true);
			model.addAttribute("errormsg", "操作失败！请先登录.");
			return "/common/error";
		}
		return "redirect:/fav/list";
	}
}
